// import './Login.scss'
// 引入antd组件
import { Row, Col, Button, Radio, Form, Input, message, Checkbox } from 'antd';
import { login } from '@/api/interface';
import { useNavigate } from 'react-router-dom'
import { useEffect } from 'react';
import { useForm } from 'antd/es/form/Form';
import './index.css'

// 登录信息初始值
let init = {
  remember: true,
  account: '',
  pw: '',
  power: "0",
}
// 自定义表单校验
const rulespw = (rule, value) => {
  if (value.length === 0) Promise.reject("密码不能为空")
  if (!(/^[\da-z]{3,8}$/.test(value))) Promise.reject("密码应该是3-8位的数字或小写字母")
    return Promise.resolve()
}

export default function index() {
  const navigate = useNavigate()
  //使用Antd的自定义Hook来获取表单域
  const [loginForm] = useForm()
  // 判断是否存储的有账号和密码
  const rememberUser = () => {
    let user = JSON.parse(localStorage.getItem('user'))
    if (user) loginForm.setFieldsValue(user)
  }
  // 初始化
  useEffect(() => {
    rememberUser()
  },[])
  
  // 表单验证成功的事件
  const onFinish = async (values) => {
      // 向服务器验证
      // let { code, token } = (await login(values)).data
      let { code, token } = {code: 0, token: '112233'}
      // console.log((await login(values)));
      if (code === 0) {
          // 服务器验证成功保存token并跳转
          sessionStorage.setItem('token', token)
          message.success('登录成功', 1)
          navigate("/")
          // 是否在本地保存账号密码
          values.remember?
              localStorage.setItem('user', JSON.stringify(values))
            :localStorage.removeItem('user')
      } else {
          // 登录失败
          onFinishFailed()
      }
  };
  // 登录失败
  const onFinishFailed = (errorInfo) => message.error('登录失败', 1)
  
  return (
    <Row className='login' >
      <Col span={6} offset={0} className='wrapper'>
        <Form
          form={loginForm}
          //标签宽度
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          // 初始值
          initialValues={init}
          autoComplete="off"
          // 提交
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
            <Form.Item
              label="账号"
              name="account"
              // 简单表单校验
              rules={[
                { required: true, message: '请输入账号！' },
                { pattern: /^\w{3,7}$/, message: '账号为3-7位的字符' }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item label="密码" name="pw" rules={[{ validator: rulespw }]}>
              <Input.Password />
            </Form.Item>
            <Form.Item label="身份" name="power">
              <Radio.Group buttonStyle="solid">
                <Radio.Button value="0">超级管理员</Radio.Button>
                <Radio.Button value="1">管理员</Radio.Button>
                <Radio.Button value="2">普通用户</Radio.Button>
              </Radio.Group>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }} name="remember" valuePropName="checked">
              <Checkbox>记住密码</Checkbox>
            </Form.Item>
            <Form.Item wrapperCol={{ span: 24, offset: 11 }}>
              <Button type="primary" htmlType="submit" size='large' className='loginbutton' >
                登录
              </Button>
            </Form.Item>
        </Form>
      </Col>
    </Row >
  )
}
